package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.domain.ForestUser;
import com.blog.domain.R;
import com.blog.service.ForestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private ForestUserService forestUserService;

    // 分页查询
    @GetMapping("/{current}/{size}")
    public R getPageAndSearch(@PathVariable("current") Integer current, @PathVariable("size") Integer size, ForestUser forestUser) {
        LambdaQueryWrapper<ForestUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(forestUser.getUserName() != null && !forestUser.getUserName().isEmpty(), ForestUser::getUserName, forestUser.getUserName());
        IPage<ForestUser> page = new Page<>(current, size);
        IPage<ForestUser> page1 = forestUserService.page(page, lqw);
        return new R(true, "查询成功", page1);
    }

    // 添加
    @PostMapping
    public R addUser(@RequestBody ForestUser forestUser) {
        return new R(forestUserService.save(forestUser), "添加成功", forestUser, 200);
    }

    // 删除
    @DeleteMapping
    public R delUser(@RequestBody List<Integer> ids) {
        boolean result = forestUserService.removeByIds(ids);
        return new R(result, result ? "删除成功" : "删除失败", 200);
    }

    // 修改
    @PutMapping
    public R putUser(@RequestBody ForestUser forestUser) {
        return new R(forestUserService.updateById(forestUser), "修改成功", forestUser, 200);
    }
}
